#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "comm.chh"

// class Init
// {
// public:
//     Init()
//     {

//     }
// };

int main()
{
    bool r = Makefile(); // 创建管道
    if (!r)
        return 1;
    // 创建共享内存
    key_t key = GetKey();
    int shmid = CreaterShm(key);
    std::cout << "server: key:" << key << ", shmid:" << shmid << std::endl;

    // 虚拟地址空间挂接
    std::cout << "server: 开始将shm映射到虚拟地址空间!" << std::endl;
    char *s = (char *)shmat(shmid, nullptr, 0);
    std::cout << s << std::endl;
    // sleep(10);

    // 打开管道
    int rfd = open(filename.c_str(), O_RDONLY);
    std::cout << filename.c_str() << ":" << rfd << std::endl;
    if (rfd < 0)
    {
        std::cout << "!!!!!!!!!!!!!" << std::endl;
        std::cerr << "errno: " << errno << "errstring: " << strerror(errno) << std::endl;
        return 1;
    }

    // TODO
    int code = 0;
    while (true)
    {
        ssize_t n = read(rfd, &code, sizeof(code));
        if (n > 0)
        {
            std::cout << "共享内存数据: " << s << std::endl;
            sleep(1);
        }
        else
        {
            break;
        }
    }

    sleep(2);
    // 移除shm映射关系
    std::cout << "server: 开始将shm从进程地址空间中移除" << std::endl;
    int shmrm = shmdt(s);
    if (shmrm == 0)
        std::cout << "server: 移除成功！" << std::endl;
    else
        std::cout << "server: 移除失败！" << std::endl;
    // sleep(2);

    // 是否共享内存空间
    std::cout << "开始将shm从OS中删除" << std::endl;
    int rm = shmctl(shmid, IPC_RMID, nullptr);
    if (rm < 0)
        std::cout << "从OS中移除失败" << std::endl;
    else
        std::cout << "从OS中成功移除" << std::endl;
    return 0;
}
